"""
Boss Agent Django视图
提供HTTP API接口
"""
import logging
import uuid

from rest_framework.exceptions import AuthenticationFailed
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from utils.JWTTool import JwtUtils
from .boss_agent import BossAgent

logger = logging.getLogger(__name__)


@method_decorator(csrf_exempt, name='dispatch')
class AgentChatView(APIView):
    """
    Agent对话接口
    
    POST /agent/chat/
    {
        "user_id": 123,
        "message": "帮我筛选Python候选人",
        "session_id": "sess_xxx"  // 可选
    }
    
    返回:
    {
        "code": 200,
        "msg": "成功",
        "data": {
            "output": "Agent回复内容",
            "session_id": "sess_xxx",
            "tool_calls": 3
        }
    }
    """

    # 单例Agent（避免每次请求重新初始化）
    _agent_instance = None
    _agent_lock = False

    @classmethod
    def get_agent(cls):
        """
        获取Agent单例
        
        使用单例模式避免每次请求都重新初始化Agent
        （Agent初始化比较耗时：加载工具、初始化LLM等）
        """
        if cls._agent_instance is None and not cls._agent_lock:
            cls._agent_lock = True
            try:
                logger.info("🚀 首次初始化Agent单例...")
                cls._agent_instance = BossAgent(verbose=False)
                logger.info("✅ Agent单例初始化成功")
            except Exception as e:
                logger.error(f"❌ Agent单例初始化失败: {str(e)}")
                cls._agent_lock = False
                raise
            finally:
                cls._agent_lock = False

        return cls._agent_instance

    def get_user_id(self, request):
        # 从Authorization header中获取token并解析用户ID
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        logger.debug(f"接收到的Authorization header: {auth_header[:20]}...")  # 只记录前20个字符，保护隐私

        if not auth_header or not auth_header.startswith('Bearer '):
            logger.warning("未提供有效的认证Token")
            raise AuthenticationFailed('未提供有效的认证Token')

        token = auth_header.split(' ')[1]
        logger.debug(f"解析出的token: {token[:20]}...")  # 只记录前20个字符

        try:
            userid = JwtUtils.get_user_id_from_token(token)
            logger.debug(f"成功解析用户ID: {userid}")
            return userid
        except Exception as e:
            logger.error(f"Token解析失败: {str(e)}")
            raise AuthenticationFailed('Token无效')

    def post(self, request):
        """
        处理对话请求
        """
        try:
            # 1. 获取参数
            # 优先从Authorization header中获取token并解析用户ID
            # 如果没有token，则从请求体中获取user_id（用于测试）
            try:
                user_id = self.get_user_id(request)
            except AuthenticationFailed:
                # 如果token认证失败，尝试从请求体获取user_id
                user_id = request.data.get('user_id')
                if user_id:
                    logger.warning(f"使用请求体中的user_id: {user_id}（仅用于开发/测试）")
                else:
                    raise
            
            message = request.data.get('message')
            session_id = request.data.get('session_id')

            # 2. 参数校验
            if not user_id:
                return Response({
                    "code": 400,
                    "msg": "缺少必填参数: user_id 或有效的认证Token"
                }, status=status.HTTP_400_BAD_REQUEST)

            if not message:
                return Response({
                    "code": 400,
                    "msg": "缺少必填参数: message"
                }, status=status.HTTP_400_BAD_REQUEST)

            # 生成session_id（如果未提供）
            if not session_id:
                session_id = f"sess_{uuid.uuid4().hex[:12]}"

            logger.info(f"\n{'=' * 60}")
            logger.info(f"📨 收到对话请求")
            logger.info(f"   User ID: {user_id}")
            logger.info(f"   Session ID: {session_id}")
            logger.info(f"   Message: {message[:100]}")
            logger.info(f"{'=' * 60}\n")

            # 3. 调用Agent
            agent = self.get_agent()
            result = agent.chat(
                user_input=message,
                user_id=user_id,
                session_id=session_id
            )

            # 4. 返回结果
            if result['success']:
                return Response({
                    "code": 200,
                    "msg": "成功",
                    "data": {
                        "output": result['output'],
                        "session_id": result['session_id'],
                        "tool_calls": result.get('tool_calls', 0)
                    }
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    "code": 500,
                    "msg": result.get('message', '处理失败'),
                    "error": result.get('error', '未知错误')
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        except Exception as e:
            logger.error(f"❌ 处理请求失败: {str(e)}", exc_info=True)
            return Response({
                "code": 500,
                "msg": "服务器错误",
                "error": str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@method_decorator(csrf_exempt, name='dispatch')
class AgentToolsView(APIView):
    """
    获取Agent工具列表
    
    GET /agent/tools/
    """

    def get(self, request):
        """
        获取工具列表
        """
        try:
            agent = AgentChatView.get_agent()
            tools = agent.get_tool_list()

            return Response({
                "code": 200,
                "msg": "成功",
                "data": {
                    "total": len(tools),
                    "tools": tools
                }
            }, status=status.HTTP_200_OK)

        except Exception as e:
            logger.error(f"获取工具列表失败: {str(e)}")
            return Response({
                "code": 500,
                "msg": "服务器错误",
                "error": str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@method_decorator(csrf_exempt, name='dispatch')
class AgentClearMemoryView(APIView):
    """
    清除会话记忆
    
    POST /agent/clear-memory/
    {
        "user_id": 123,
        "session_id": "sess_xxx"
    }
    """

    def post(self, request):
        """
        清除指定会话的记忆
        """
        try:
            user_id = request.data.get('user_id')
            session_id = request.data.get('session_id')

            if not user_id or not session_id:
                return Response({
                    "code": 400,
                    "msg": "缺少必填参数: user_id, session_id"
                }, status=status.HTTP_400_BAD_REQUEST)

            agent = AgentChatView.get_agent()
            success = agent.clear_memory(user_id, session_id)

            if success:
                return Response({
                    "code": 200,
                    "msg": "记忆已清除"
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    "code": 500,
                    "msg": "清除失败"
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        except Exception as e:
            logger.error(f"清除记忆失败: {str(e)}")
            return Response({
                "code": 500,
                "msg": "服务器错误",
                "error": str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
